﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FZKJ.COMMON;
using FZKJ.Model;
using FZKJ.ZHXJ.Models;
using Newtonsoft.Json;
using System.IO;
using System.Transactions;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;

namespace FZKJ.ZHXJ.Controllers
{
    public class RescueCardController : Controller
    {
        //
        // GET: /RescueCard/

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 救援卡登记
        /// </summary>
        /// <returns></returns>
        public ActionResult EntryRescue()
        {
            return View();
        }



        public string GetCards()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织
            var where = string.Empty;
            if (!string.IsNullOrWhiteSpace(Request.Params["query"]))
            {
                where += $" (T.cardno like'%{Request.Params["query"]}%' OR D.name like'%{Request.Params["query"]}%' OR D.mobile like'%{Request.Params["query"]}%') AND ";
            }

            if (!string.IsNullOrWhiteSpace(Request.Params["startTime"]))
            {
                where += $" T.createtime>='{Request.Params["startTime"]}' AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["startTime"]))
            {
                where += $" T.createtime<='{Request.Params["endTime"]}' AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["carstate"]))
            {
                where += $" activationstate={Request.Params["carstate"]} AND ";
            }

            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_card().GetListByPage(where, order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_card().GetListByPage(where, "", -1, -1).Tables[0].Rows.Count;
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }

        [HttpPost]
        public string SaveCard(string json)
        {
            var result = new ResultInfo(false);
            var userInfo = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
            var bll = new BLL.buss_card();
            var model = JsonConvert.DeserializeObject<CardModel>(json);
            var list = new List<Model.buss_card>();
            try
            {
                bool isExist = false;
                int number = 0;
                string basecode = "ZHXJ" + DateTime.Now.ToString("yyyyMMdd");
                string where = "";
                for (int i = model.startcard; i <= model.endcard; i++)
                {

                    string code = basecode + i.ToString().PadLeft(5, '0');
                    where += "'" + code + "',";
                    var m = new buss_card
                    {
                        id = Guid.NewGuid().ToString().Replace("-", "").ToLower(),
                        cardno = code,
                        cardtype = model.cardtype,
                        activationstate = 0,
                        createtime = DateTime.Now,
                        starttime = model.starttime,
                        endtime = model.endtime,
                        origin = model.origin,
                        password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.origin, "MD5")
                    };
                    list.Add(m);
                }

                if (where.Length > 0)
                    where = where.Remove(where.Length - 1);
                var list2 = new BLL.buss_card().GetModelList(" cardno in(" + where + ")");

                if (list2.Count > 0)
                {
                    result.IsSucceed = false;
                    result.Message = basecode + number.ToString().PadRight(5, '0') + "已存在";
                }
                else
                {
                    bll.Add(list);
                    result.IsSucceed = true;
                    result.Message = "批量生成卡号生成成功";
                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "生成失败";
            }

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string SaveOneCard(string json)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_card>(json);
                model.password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.origin, "MD5");
                var user = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                if (model.id == "-1")
                {
                    model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    if (new BLL.buss_card().ExistsCode(model.cardno))
                    {
                        result.IsSucceed = false;
                        result.Message = "卡号重复";
                    }
                    else
                    {
                        model.createtime = DateTime.Now;
                        model.creator = Convert.ToInt32(user[0].id);
                        new BLL.buss_card().Add(model);
                        result.IsSucceed = true;
                        result.Message = "添加成功";
                    }
                }
                else
                {
                    var m = new BLL.buss_card().GetModel(model.id);
                    var list = new BLL.buss_card().GetModelList(" cardno='" + m.cardno + "' and id!='" + m.id + "'");
                    if (list.Count > 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "卡号重复";

                    }
                    else
                    {
                        m.origin = model.origin;
                        m.password = model.password;
                        m.cardtype = model.cardtype;
                        m.starttime = model.starttime;
                        m.endtime = model.endtime;
                        new BLL.buss_card().Update(m);
                        result.IsSucceed = true;
                        result.Message = "添加成功";
                    }

                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);

        }

        /// <summary>
        /// 救援卡激活管理
        /// </summary>
        /// <returns></returns>
        public ActionResult ActivationManage(string id, string actions)
        {
            var dt = new BLL.buss_members().GetMemberCard(id);
            ViewData["dt"] = dt;
            ViewBag.action = actions;
            return View();
        }

        [HttpPost]
        public string ActivityZHXJ(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var member = JsonConvert.DeserializeObject<Model.buss_members>(json);
                var car = JsonConvert.DeserializeObject<Model.buss_memberCar>(json);
                car.option1 = null;
                var card = JsonConvert.DeserializeObject<Card>(json);
                var policy = JsonConvert.DeserializeObject<Model.buss_insurance>(json);
                member.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                car.memberId = member.id;
                policy.memberid = member.id;
                var list = new BLL.buss_card().GetModelList("cardno='" + card.card + "'");
                if (list.Count == 0)
                {
                    result.IsSucceed = false;
                    result.Message = "不存在该卡号";
                }
                else
                {
                    list = list.Where(p => p.activationstate == 0).ToList();
                    if (list.Count == 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "该卡号不是处于待激活状态";
                    }
                    else
                    {
                        var m = list[0];
                        if (m.password != System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(card.password, "MD5"))
                        {
                            result.IsSucceed = false;
                            result.Message = "密码错误";
                        }
                        else
                        {
                            m.activationstate = 1;
                            policy.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                            policy.memberid = member.id;
                            var member_card = new Model.buss_rescue
                            {
                                id = Guid.NewGuid().ToString().ToLower(),
                                memberid = member.id,
                                rescuecard = m.cardno,
                                rescuestart = m.starttime,
                                rescueend = m.endtime
                            };
                            member.code = GenerateCode.GetCode();
                            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                            {
                                var members = new BLL.buss_members().GetModelList(" mobile='" + member.mobile + "'");
                                if (members.Count == 0)
                                {
                                    new BLL.buss_members().Add(member);
                                }
                                else
                                {
                                    member.id = members[0].id;
                                    member.code = members[0].code;
                                    member.openid = members[0].openid;
                                    member.headImg = members[0].headImg;
                                    member.nickName = members[0].nickName;
                                    member.city = members[0].city;
                                    member.country = members[0].country;
                                    member.password = members[0].password;
                                    new BLL.buss_members().Update(member);
                                }

                                new BLL.buss_card().Update(m);
                                member_card.memberid = member.id;
                                new BLL.buss_rescue().Add(member_card);
                                policy.memberid = member.id;
                                new BLL.buss_insurance().Add(policy);
                                car.memberId = member.id;
                                new BLL.buss_memberCar().Add(car);
                                scope.Complete();
                            }
                            result.IsSucceed = true;
                            result.Message = "激活成功";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "激活失败";
            }
            return JsonConvert.SerializeObject(result);
        }


        public string UploadFile(string path)
        {
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string path1 = Server.MapPath("~/Resourse/");
            string returnPath = "";
            string fileName = "";
            string newName = Guid.NewGuid().ToString().Replace("-", "");
            if (!Directory.Exists(path1))//不存在这个文件夹就创建这个文件夹 
            {
                Directory.CreateDirectory(path1);
            }
            if (hfc.Count > 0)
            {
                fileName = hfc[0].FileName;
                newName = newName + "." + hfc[0].FileName.Split('.')[1].ToLower();
                hfc[0].SaveAs(path1 + newName);
            }
            else
            {
                return "0";
            }

            return newName;
        }

        /// <summary>
        /// 营运车辆激活
        /// </summary>
        /// <returns></returns>
        public ActionResult Car()
        {
            return View();
        }
        [HttpPost]
        public string ActivityCars(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var model = JsonConvert.DeserializeObject<Model.buss_vehicle>(json);
                var list = new BLL.buss_vehicle().GetModelList(" carowner='" + model.carowner + "' and carmodel='" + model.carmodel + "' and licenseplate='" + model.licenseplate + "' and drivingnumber='" + model.drivingnumber + "' and enginenumber='" + model.enginenumber + "' and pedestal='" + model.pedestal + "' and mobile='" + model.mobile + "'");
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var currentMember = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                if (currentMember.Count > 0)
                {
                    if (list.Count == 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "车辆不存在";
                    }
                    else
                    {
                        foreach (var item in list)
                        {
                            item.activityState = 1;
                            item.option1 = currentMember[0].id.ToString();
                            new BLL.buss_vehicle().Update(item);
                        }
                        result.IsSucceed = true;
                        result.Message = "激活成功";
                        PublicClass.AddLog("操作", "激活营运车辆" + model.licenseplate);
                    }
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "暂未登录";
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }


        public ActionResult CarUpgrade()
        {
            return View();
        }

        public string GetUpGrades()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织
            var where = string.Empty;
            if (!string.IsNullOrWhiteSpace(Request.Params["query"]))
            {
                where += $" name like'%{Request.Params["query"]}%' AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["state"]))
            {
                where += $" dealResult ='{Request.Params["state"]}' AND ";
            }
            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_cardupgrade().GetListByPage(where, order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_cardupgrade().GetListByPage(where, "", -1, -1).Tables[0].Rows.Count;
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }
        public string ReviewCard()
        {
            ResultInfo result = new ResultInfo(false);
            string str = "";
            try
            {
                var file = Request.Files[0];
                string extends = file.FileName.Split('.')[1];
                if (extends != "xlsx" && extends != "xls")
                {
                    result.IsSucceed = false;
                    result.Message = "请上传正确格式的excel表格！";
                }
                else
                {

                    var reflist = FileToEntity.FileToEntityFunc<ActivityCard>(HttpContext, "保单数据", "policy.json", file);
                    LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                    var currentMember = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                    {
                        foreach (var item in reflist)
                        {
                            //if (list.Count == 0)
                            //{
                            //    str = $"卡号为{item.cardno}的卡未找到\r\n";
                            //}
                            //else
                            //{
                            var member = new BLL.buss_members().GetModelList(" cardno=" + item.cardno + "'");
                            if (member.Count == 0)
                            {
                                str += $"身份证号为{item.card}的会员未找到\r\n";
                            }
                            else
                            {
                                if (item.isactivity == "是")
                                {
                                    member[0].isgloabl = 1;
                                    new BLL.buss_members().Update(member[0]);
                                }
                                var list = new BLL.buss_cardupgrade().GetModelList(" userId='" + member[0].isdel + "' and dealResult='0'");
                                var model = list[0];
                                model.cardno = item.cardno;
                                model.dealResult = item.isactivity == "是" ? "1" : "2";
                                model.dealTime = DateTime.Now;
                                new BLL.buss_cardupgrade().Update(model);
                            }
                        }
                        //}
                        scope.Complete();

                    }
                }
                result.IsSucceed = true;
                result.Message = string.IsNullOrWhiteSpace(str) ? "导入成功" : str;
            }

            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }
        [HttpPost]
        public string PassOrNoPass(string ids, string state)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                string where = "";
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    foreach (var item in ids.Split(','))
                    {
                        var model = new BLL.buss_cardupgrade().GetModel(int.Parse(item));
                        model.dealResult = state;
                        new BLL.buss_cardupgrade().Update(model);
                        var member = new BLL.buss_members().GetModelList(" id='" + model.userId + "'");
                        if (member.Count > 0)
                        {
                            var ite = member[0];
                            if (state == "1")
                            {
                                ite.isgloabl = 1;
                                new BLL.buss_members().Update(ite);
                            }
                        }
                    }
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = "操作失败";
            }
            return JsonConvert.SerializeObject(result);
        }
        [HttpPost]
        public string DeleteCard(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                foreach (var item in ids.Split(','))
                {
                    var model = new BLL.buss_card().GetModel(item);
                    if (model.isusestatus == 1)
                    {
                        result.IsSucceed = false;
                        result.Message = "已发放实体卡，不能删除";
                    }
                    else if (model.activationstate == 1)
                    {
                        result.IsSucceed = true;
                        result.Message = "已激活，不能被删除";
                    }
                    else
                    {
                        new BLL.buss_card().Delete(item);
                        result.IsSucceed = true;
                        result.Message = "删除成功";
                    }
                }
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "删除失败";
            }
            return JsonConvert.SerializeObject(result);
        }
        [HttpPost]
        public string UpdateIsusestatus(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    foreach (var item in ids.Split(','))
                    {
                        var model = new BLL.buss_card().GetModel(item);
                        model.isusestatus = 1;
                        new BLL.buss_card().Update(model);
                    }
                    scope.Complete();
                }

                result.IsSucceed = true;
                result.Message = "发放成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "发放失败";
            }
            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string RecoveryCard(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    foreach (var item in ids.Split(','))
                    {
                        var model = new BLL.buss_card().GetModel(item);
                        model.isusestatus = 0;
                        new BLL.buss_card().Update(model);
                    }
                    scope.Complete();
                }

                result.IsSucceed = true;
                result.Message = "回收发放成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "回收发放失败";
            }
            return JsonConvert.SerializeObject(result);
        }
        [HttpPost]
        public string ToExcel(string ids)
        {
            //模板文件
            string TempletFileName = Server.MapPath("~/template/升级管理激活请求模板.xlsx");
            string name = "激活请求数据" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
            //导出文件
            if (!Directory.Exists(Server.MapPath("~/Out/")))
            {
                Directory.CreateDirectory(Server.MapPath("~/Out/"));
            }
            string ReportFileName = Server.MapPath("~/Out/" + name);
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
            XSSFSheet ws = (XSSFSheet)hssfworkbook.GetSheet("Sheet1");
            string where = " id in (";
            foreach (var item in ids.Split(','))
            {
                where += "'" + item + "',";
            }

            where = where.Remove(where.Length - 1);
            where += ")";

            //添加或修改WorkSheet里的数据
            var dt = new BLL.buss_cardupgrade().GetListByPage(where, "", -1, -1).Tables[0];
            #region
            int i = 1;
            int j = 0;
            if (dt.Rows.Count > 0)
            {
                for (; j < dt.Rows.Count; j++)
                {
                   ws.CreateRow(i);
                    ws.GetRow(i).CreateCell(0).SetCellValue(dt.Rows[j]["name"].ToString());
                    ws.GetRow(i).CreateCell(1).SetCellValue(dt.Rows[j]["mobile"].ToString());
                    ws.GetRow(i).CreateCell(2).SetCellValue(dt.Rows[j]["card"].ToString());
                    ws.GetRow(i).CreateCell(3).SetCellValue(dt.Rows[j]["cardno"].ToString());
                    i++;
                }
            }
            #endregion
            ws.ForceFormulaRecalculation = true;

            using (FileStream filess = System.IO.File.OpenWrite(ReportFileName))
            {
                hssfworkbook.Write(filess);
            }

            //filess.Close();


            System.IO.FileInfo filet = new System.IO.FileInfo(ReportFileName);
            return name;
        }
    }

    public class ActivityCard
    {
        public string card { get; set; }
        public string cardno { get; set; }
        public string isactivity { get; set; }
    }
}
